package org.dc.agent.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.log4j.Logger;
import org.dc.agent.configoper.GetConfig;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @category 数据库连接
 * 
 * */
public class DBPool {

	private static Logger logger = Logger.getLogger(DBPool.class);
	private static DBPool dbPool;
	private ComboPooledDataSource dataSource;

	static {
		dbPool = new DBPool();
	}

	private DBPool() {

		try {
			dataSource = new ComboPooledDataSource();
			dataSource.setUser(GetConfig.getValue("database.userName"));
			dataSource.setPassword(GetConfig.getValue("database.password"));
			dataSource.setJdbcUrl(GetConfig.getValue("database.jdbcUrl"));
			dataSource.setDriverClass(GetConfig
					.getValue("database.driverClass"));
			dataSource.setInitialPoolSize(1);
			dataSource.setMinPoolSize(Integer.parseInt(GetConfig
					.getValue("MIN_POOL_SIZE")));
			dataSource.setMaxPoolSize(Integer.parseInt(GetConfig
					.getValue("MAX_POOL_SIZE")));
			dataSource.setMaxStatements(2);
			dataSource.setMaxIdleTime(60);
			dataSource.setCheckoutTimeout(0);

		} catch (PropertyVetoException e) {
			logger.error("PropertyVetoException", e);
		}
	}

	public final static DBPool getInstance() {
		return dbPool;
	}

	public final Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			logger.error("SQLException", e);
		}
		return null;
	}

}
